package com.education.controller.backend;

import com.education.pojo.HistoryScore;
import com.education.pojo.Question;
import com.education.pojo.TestPaper;
import com.education.pojo.UserError;
import com.education.service.WZJService;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2018/4/28.
 */
@Controller
public class WZJController {
    /**
     * （吴）注入service层
     */
    @Autowired
    private WZJService wzjServiceImpl;

    @CrossOrigin
    @RequestMapping("/listQuestion")
    @ResponseBody
    //获取问题表中问题的数据，返还到前台
    public List<Question> getList(@RequestBody Question questionRequest
    ){
        Integer tpId = questionRequest.getTpId();
        List<Question> list = wzjServiceImpl.queryQuestionListPage(tpId);
        return list;
    }

    /**
     *
     * @param userError
     * @param historyScore
     * @param request
     * @return
     * 根据用户答题情况，判断用户的历史成绩，用户的错题情况。
     * 这里的返回值类型是double主要是为了返回答案
     */
    @CrossOrigin
    @RequestMapping("/submitAnswerAll")
    @ResponseBody
//    public double addUserErrorAndHistoryScore(UserError userError, HistoryScore historyScore, HttpServletRequest request){
//        System.out.println("qing qiu ");
//        Integer uid = Integer.parseInt(request.getParameter("uid"));//用户的ID
//        Integer tpid = Integer.parseInt(request.getParameter("tpid"));//试卷ID
//        String qd = request.getParameter("qd");//题目ID  数组
//        String uenswer = request.getParameter("uenswer");// 用户填写的答案  数组
//        Integer total = Integer.parseInt(request.getParameter("total"));
//
//        JSONArray jsonQId = JSONArray.fromObject(qd);
//        JSONArray jsonUenswer = JSONArray.fromObject(uenswer);
//        double scoreAverage = 100/total;
//        double score = 0.0;
//            for (int i = 0; i < jsonQId.size(); i++) {
//                Integer qId = Integer.parseInt(jsonQId.get(i).toString());
//                /*遍历用户答案uenswe
//                 * 遍历正确答案questionAnswer
//                 * 比较两者是否一致，判断用户是否正确
//                 * 正确加10分，错误不加分，并将用户回答的错误答案以及该题的ID号得到存储到错误表中
//                 */
//                String uenswe = jsonUenswer.get(i).toString();
//                String questionAnswer = wzjServiceImpl.queryQuestionAnswerList(tpid).get(i).getqAnswerTrue();
//               /*
//               同时查询本用户是否之前也做错过相同题目，若也错过，则将之前的错误修改保存
//               以此保证每套题用户只需要查询到最新的一次错误
//                */
//                if(uenswe.equals(questionAnswer)){
//                    score += scoreAverage;
//                } else {
//                    if(uenswe.trim().length() == 0){
//                        uenswe = "未选择答案";
//                    }
//                    //多个参数传值问题方式二
////                    Map map = new HashMap();
////                    map.put("qId",qId);
////                    map.put("uId",uid);
//                    if (
//                            wzjServiceImpl.queryUserErrorHistoryQidMessage(qId,uid) == 0
////                            wzjServiceImpl.queryUserErrorHistoryQidMessage(map) == 0
//                            ){
//                        userError.setUeAnswer(uenswe);
//                        userError.setqId(qId);
//                        userError.setuId(uid);
//                        wzjServiceImpl.addUserErrorMessage(userError);
//                    } else {
//                        userError.setUeAnswer(uenswe);
//                        userError.setqId(qId);
//                        userError.setuId(uid);
//                        wzjServiceImpl.modifyUserErrorHistoryQidMessage(userError);
//                    }
//
//                }
//            }
//             /*
//            根据得到的score分数，存储到用户历史成绩当中
//            */
//            historyScore.setuId(uid);
//            historyScore.setTpId(tpid);
//            historyScore.setHsScore(score);
//            wzjServiceImpl.addHistoryScoreMessage(historyScore);
//            return score;
//    }


    public double addUserErrorAndHistoryScore(UserError userError, HistoryScore historyScore, HttpServletRequest request){
        System.out.println("qing qiu ");
        Integer uid = Integer.parseInt(request.getParameter("uid"));//用户的ID
        Integer tpid = Integer.parseInt(request.getParameter("tpid"));//试卷ID
        String qd = request.getParameter("qd");//题目ID  数组
        String uenswer = request.getParameter("uenswer");// 用户填写的答案  数组
        Integer total = Integer.parseInt(request.getParameter("total"));

        JSONArray jsonQId = JSONArray.fromObject(qd);
        JSONArray jsonUenswer = JSONArray.fromObject(uenswer);
        double scoreAverage = 100/total;
        double score = 0.0;
        for (int i = 0; i < jsonQId.size(); i++) {
            Integer qId = Integer.parseInt(jsonQId.get(i).toString());
                /*遍历用户答案uenswe
                 * 遍历正确答案questionAnswer
                 * 比较两者是否一致，判断用户是否正确
                 * 正确加10分，错误不加分，并将用户回答的错误答案以及该题的ID号得到存储到错误表中
                 */
            String uenswe = jsonUenswer.get(i).toString();
            String questionAnswer = wzjServiceImpl.queryQuestionAnswerList(tpid).get(i).getqAnswerTrue();
               /*
               同时查询本用户是否之前也做错过相同题目，若也错过，则将之前的错误修改保存
               以此保证每套题用户只需要查询到最新的一次错误
                */
            if(uenswe.equals(questionAnswer)){
                score += scoreAverage;
            } else {
                if(uenswe.trim().length() == 0){
                    uenswe = "未选择答案";
                }
                userError.setUeAnswer(uenswe);
                userError.setqId(qId);
                userError.setuId(uid);
                wzjServiceImpl.addUserErrorMessage(userError);
            }
        }
             /*
            根据得到的score分数，存储到用户历史成绩当中
            */
        historyScore.setuId(uid);
        historyScore.setTpId(tpid);
        historyScore.setHsScore(score);
        wzjServiceImpl.addHistoryScoreMessage(historyScore);
        return score;
    }

    /**
     *
     * @param request
     * @return
     * 根据用户ID 查询出他对应的错题试卷名称
     */
    @CrossOrigin
    @RequestMapping("/seleteUserErrorQid")
    @ResponseBody
//    public Map<String, List> getUserErrorQidList(HttpServletRequest request){
//        List<String> userErrorTpNameList = new ArrayList<String>();//装的查询到用户错题库的名称集合
//        List<Integer> userErrorTpIdList = new ArrayList<Integer>();//因为tpid之前查到使用set集合装的，现在要传
//        //到前台去，为了确保试卷的TPID和试卷的名称一一对应，所以用这个集合在装一下tpid
//        Map<String,List> map = new HashMap<String, List>();//通过map集合，将查询到的不同集合传到前台
//        Integer uqid = Integer.parseInt(request.getParameter("uId"));
//        List<UserError> qIdList = wzjServiceImpl.queryUserErrorQidMessage(uqid);//根据用户的ID和查询的时间范围查询他的错题QID
//        Set<Integer> tpIdList = new HashSet<Integer>();//为了确保查询的试卷tpid不重复用的set集合来装
//        for(int i = 0;i<qIdList.size();i++){
//           Integer tpIdOne = wzjServiceImpl.queryUserErrorTpidList(qIdList.get(i));//根据得到用户的Qid查到对应的试卷tpid
//           tpIdList.add(tpIdOne);
//        }
//        for (Integer tpId:tpIdList
//                ) {
//            userErrorTpIdList.add(tpId);
//            userErrorTpNameList.add(wzjServiceImpl.queryUserErrorTpNameList(tpId));
//        }
//        //这种方式迭代有问题
////        while (tpIdList.iterator().hasNext()){
////            userErrorTpNameList.add(wzjServiceImpl.queryUserErrorTpNameList(tpIdList.iterator().next()));
////        }
//        map.put("userErrorTpIdList",userErrorTpIdList);
//        map.put("userErrorTpNameList",userErrorTpNameList);
//        return map;
//    }
    public Map<String, List> getUserErrorQidList(HttpServletRequest request){
        List<String> userErrorUeCreatTime = new ArrayList<String>();
        List<String> userErrorTpNameList = new ArrayList<String>();//装的查询到用户错题库的名称集合
        List<Integer> userErrorTpIdList = new ArrayList<Integer>();//因为tpid之前查到使用set集合装的，现在要传
        //到前台去，为了确保试卷的TPID和试卷的名称一一对应，所以用这个集合在装一下tpid
        Map<String,List> map = new HashMap<String, List>();//通过map集合，将查询到的不同集合传到前台
        Integer uqid = Integer.parseInt(request.getParameter("uId"));
        String timeFrame = request.getParameter("timeFrame")+":00";
        //根据用户的ID和查询的时间范围，并且根据时间分组，避免同一套题就只需要有一个qid作为查询依据即可
        List<UserError> qIdTimeList = wzjServiceImpl.queryUserErrorQidMessage(uqid,timeFrame);
        List<Integer> tpIdList = new ArrayList<Integer>();//试卷tpid集合来装
        for(int i = 0;i<qIdTimeList.size();i++){
                    Integer tpIdOne = wzjServiceImpl.queryUserErrorTpidList(qIdTimeList.get(i).getqId());//根据得到用户的Qid查到对应的试卷tpid
                    tpIdList.add(tpIdOne);
                    //将查询到的时间转换成字符串，传到前台使用
                    SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss  " );
                    String strTime = sdf.format(qIdTimeList.get(i).getUeCreateTime());
                    userErrorUeCreatTime.add(strTime);
        }
        for (Integer tpId:tpIdList
                ) {
            userErrorTpIdList.add(tpId);
            userErrorTpNameList.add(wzjServiceImpl.queryUserErrorTpNameList(tpId));
        }
        //这种方式迭代有问题
//        while (tpIdList.iterator().hasNext()){
//            userErrorTpNameList.add(wzjServiceImpl.queryUserErrorTpNameList(tpIdList.iterator().next()));
//        }

        map.put("userErrorTpIdList",userErrorTpIdList);
        map.put("userErrorTpNameList",userErrorTpNameList);
        map.put("userErrorUeCreatTime",userErrorUeCreatTime);
        return map;
    }

    /**
     *
     * @param
     * @return
     * 根据用户选择的错误试卷回顾，首先根据TPID查询本试卷的错误题目就（错题库），确定QID并将
     * 用户的错误答案查询到；然后根据查询到的QID查询到相应的题目（题库），得到q_order、
     * q_name、q_answer等信息
     */
    @CrossOrigin
    @RequestMapping("/errorQuestionListView")
    @ResponseBody
    public Map<String,List> getUserErrorPageView(TestPaper testPaper,UserError userError,HttpServletRequest request){
        Integer tpId = testPaper.getTpId();
        Integer uId = userError.getuId();
        String ueCreateTime=request.getParameter("userErrorUeCreatTime");
        //存储用户的错误答案集合
        List<String> ueAnswerList = new ArrayList<String>();
        // 存储用户错误题的题目信息
        List<Question> userErrorQuestionList = new ArrayList<Question>();
        //根据tpid查询到对应的qid
        Map<String,List> map = new HashMap<String,List>();
        List<Integer> listQid = wzjServiceImpl.queryQidUseUserErrorQidList(tpId);
        for (int i = 0;i<listQid.size();i++){
            String ueAnswer = wzjServiceImpl.queryUeAnswerOneMessage(listQid.get(i),uId,ueCreateTime);
            if(ueAnswer != null){
                ueAnswerList.add(ueAnswer);
                //将用户回答错误的题，对应的查询到
                userErrorQuestionList.add(wzjServiceImpl.queryUserErrorQuestionListMessage(listQid.get(i)));
            }
        }
        map.put("ueAnswerList",ueAnswerList);
        map.put("userErrorQuestionList",userErrorQuestionList);
        return map;
    }

    /*
    用户查询历史成绩
     */
    @CrossOrigin
    @RequestMapping("/seleteUserHistoryScore")
    @ResponseBody
    public Map<String,List> getUserHistoryScore(HistoryScore historyScore){
        Integer uId = historyScore.getuId();
        List<String> historyScoreTpNameList = new ArrayList<String>();
        Map<String,List> map = new HashMap<>();
        List<HistoryScore> historyScoresList = wzjServiceImpl.queryUserHistoryScore(uId);
        for (int i = 0;i<historyScoresList.size();i++){
            //获取试卷名
            historyScoreTpNameList.add(wzjServiceImpl.queryUserErrorTpNameList(historyScoresList.get(i).getTpId()));
        }
        map.put("historyScoresList",historyScoresList);
        map.put("historyScoreTpNameList",historyScoreTpNameList);
        return  map;
    }

}
